﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Lamex.mNC.Common
{
    public class FileHelper
    {

        public static bool IsPermissionByMove(string CurrentSate, string ConvertType, string strNumber, string LockMan)
        {
            string strPath;
            if (CurrentSate == "已转码" || CurrentSate == "审核中")
            {
                switch (ConvertType)
                {
                    case "DESK_SJR":
                        strPath = ReturnXmlPath("NC_DK_SJ01");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "DESK_STD":
                        strPath = ReturnXmlPath("NC_DK_STD01");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "PANEL_STR":
                        strPath = ReturnXmlPath("NC_AL_SJ01");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "PANEL_STD":
                        strPath = ReturnXmlPath("NC_AL_STD01");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                }
            }
            else if (CurrentSate == "已审核")
            {
                switch (ConvertType)
                {
                    case "DESK_SJR":
                        strPath = ReturnXmlPath("NC_DK_SJ02");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "DESK_STD":
                        strPath = ReturnXmlPath("NC_DK_STD02");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "PANEL_STR":
                        strPath = ReturnXmlPath("NC_AL_SJ02");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                    case "PANEL_STD":
                        strPath = ReturnXmlPath("NC_AL_STD02");
                        if (IsFilePower(strPath, strNumber, LockMan))
                            return true;
                        else
                            return false;
                }
            }
            return true;
        }
        public static void CopyMoveFile(string CurrentSate, string ConvertType, string strNumber)
        {
            string strPath = "";
            string strTargetPath = ReturnXmlPath("NcTargetPath");
            if (CurrentSate == "已转码" || CurrentSate == "审核中")
            {
                switch (ConvertType)
                {
                    case "DESK_SJR":
                        strPath = ReturnXmlPath("NC_DK_SJ01");
                        //File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        //File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "DESK_STD":
                        strPath = ReturnXmlPath("NC_DK_STD01");
                        // File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        // File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "PANEL_STR":
                        strPath = ReturnXmlPath("NC_AL_SJ01");
                        // File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        // File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "PANEL_STD":
                        strPath = ReturnXmlPath("NC_AL_STD01");
                        //File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        //File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                }
                if (!Directory.Exists(strTargetPath))//判断配置路径是否存在
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("配置路径NcTargetPath不存在,文件不会被转移！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return false;
                }
                else
                    FolderMove(strPath + @"\" + strNumber, strTargetPath + @"\" + strNumber);
                // return true;
            }
            else if (CurrentSate == "已审核")
            {
                switch (ConvertType)
                {
                    case "DESK_SJR":
                        strPath = ReturnXmlPath("NC_DK_SJ02");
                        // File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        // File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "DESK_STD":
                        strPath = ReturnXmlPath("NC_DK_STD02");
                        //File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        // File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "PANEL_STR":
                        strPath = ReturnXmlPath("NC_AL_SJ02");
                        // File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        //File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                    case "PANEL_STD":
                        strPath = ReturnXmlPath("NC_AL_STD02");
                        // File.Copy(strPath + @"\" + strNumber + ".csv", strTargetPath + @"\" + strNumber + ".csv", true);
                        // File.Delete(strPath + @"\" + strNumber + ".csv");
                        break;
                }
                if (!Directory.Exists(strTargetPath))//判断配置路径是否存在
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("配置路径NcTargetPath不存在,文件不会被转移！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // return false;
                }
                else
                    FolderMove(strPath + @"\" + strNumber, strTargetPath + @"\" + strNumber);
                // return true;
            }
            // return false;
        }

        public static bool IsFilePower(string strPath, string strNumber, string LockMan)
        {

            if (CheckWritePermissionOnDir(strPath))
            {
                string strCurrent = strPath + @"\" + strNumber;
                string strReName = strPath + @"\" + strNumber + "_1";//虚拟的文件夹名称
                if (Directory.Exists(strCurrent))//文件夹存在
                {
                    //判断文件是否被占用
                    DirectoryInfo root = new DirectoryInfo(strCurrent);
                    foreach (FileInfo f in root.GetFiles())
                    {
                        if (!IsFileInUse(f.FullName))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("当前文件:" + f.FullName + "\r\n" + "被" + LockMan + "占用,请通知退出占用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                    }
                    //判断文件夹是否被占用
                    if (!IsFolderInUse(strCurrent, strReName))
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("当前文件夹:" + strCurrent + "\r\n" + "被" + LockMan + "占用,请通知退出占用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    //string sourceFolderName = @"L:\LAMEX\NC\Converting\Desk\DK_SJ\2_已上载\3960400024";
                    //string destFolderName = @"L:\LAMEX\NC\Converting\Desk\DK_SJ\2_已上载\3960400024_1";

                    //Directory.Move(sourceFolderName, destFolderName);
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("当前文件夹:" + strCurrent + "不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                return true;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("没有访问桌子SJ已转码路径的权限，请联系MES管理员开通！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        public static string ReturnXmlPath(string strName)
        {
            string strPath = "";
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;

            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                foreach (XmlElement x2 in xn2)
                {
                    if (x2.Name == strName)
                        strPath = x2.InnerText;
                }
            }
            return strPath;
        }
        /// <summary>
        /// 检查当前用户是否有文件夹操作权限
        /// </summary>
        /// <param name="path">文件夹所在的路径</param>
        /// <returns></returns>
        public static bool CheckWritePermissionOnDir(string path)
        {
            try
            {
                if (!string.IsNullOrEmpty(path))
                {
                    //排除本地磁盘
                    if (IsFixedDisk(path.Substring(0, 2)))
                        return true;
                    else
                    {
                        //获取当前登录用户
                        var currentUserIdentity = Path.Combine(Environment.UserDomainName, Environment.UserName);
                        //获取文件夹的权限/安全信息
                        DirectorySecurity fileAcl = Directory.GetAccessControl(path);
                        //当前用户对文件夹的权限信息
                        var userAccessRules = fileAcl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)).OfType<FileSystemAccessRule>().Where(i => i.IdentityReference.Value == currentUserIdentity).ToList();
                        //是否有Allow权限
                        return userAccessRules.Any(i => i.AccessControlType == AccessControlType.Allow);
                    }
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 检查当前文件是否被占用
        /// </summary>
        /// <param name="fileName">当前文件的完整路径</param>
        /// <returns></returns>
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = false;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite,
                FileShare.None);
                inUse = true;
            }
            catch
            {

            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;
        }
        public static bool IsFolderInUse(string sourceFolderName, string destFolderName)
        {
            bool inUse = false;
            try
            {
                //解除Creo软件占用文件夹
                UnLockDir();
                //重命名文件夹，检查是否被占用
                Directory.Move(sourceFolderName, destFolderName);
                //再反转一次
                Directory.Move(destFolderName, sourceFolderName);
                inUse = true;
            }
            catch
            {

            }
            return inUse;
        }


        /// <summary>
        /// 文件夹移动-并删除当前文件夹
        /// </summary>
        /// <param name="srcFolderPath">当前文件夹路径</param>
        /// <param name="destFolderPath">目标文件夹路径</param>
        public static void FolderMove(string srcFolderPath, string destFolderPath)
        {
            //检查目标目录是否以目标分隔符结束，如果不是则添加之
            if (destFolderPath[destFolderPath.Length - 1] != Path.DirectorySeparatorChar)
                destFolderPath += Path.DirectorySeparatorChar;
            //判断目标目录是否存在，如果不在则创建之
            //判断目标目录是否存在，如果不在则创建之
            if (Directory.Exists(destFolderPath))//文件夹存在
            {
                DirectoryInfo di = new DirectoryInfo(destFolderPath);
                di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
            }
            Directory.CreateDirectory(destFolderPath);//创建文件夹

            string[] fileList = Directory.GetFileSystemEntries(srcFolderPath);

            foreach (string file in fileList)
            {
                if (Directory.Exists(file))
                {
                    FolderMove(file, destFolderPath + Path.GetFileName(file));
                    //Directory.Delete(file);
                }
                else
                    File.Move(file, destFolderPath + Path.GetFileName(file));
            }
            Directory.Delete(srcFolderPath);
        }

        //判断磁盘类型
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetDriveType(string driveinfo);
        private enum DriveType
        {
            NotExist = 1,
            FloppyOrUsb = 2,
            FixedDisk = 3,
            NetDisk = 4,
            CDRom = 5,
            RAMDisk = 6
        }
        public static bool IsFixedDisk(string driveInfo)
        {
            if (driveInfo == null || driveInfo == "")
                return false;
            if (GetDriveType(driveInfo) == (int)DriveType.FixedDisk)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //解除文件夹占用--只能用于Creo软件解除
        [DllImport("MCreoDll.dll", CharSet = CharSet.Ansi)]
        public static extern void setDir();
        public static void UnLockDir()
        {
            try
            {
                setDir();
            }
            catch
            {
            }
        }
    }
}
